package vigenere;

public class Kodieren {

	private final String code;
	private int counter;

	public Kodieren(String code) {
		this.code = code;

	}

	// smallest character we work with is 'A'
	public static int SMALLEST_CHAR = 0x41;
	// biggest character we work with is 'Z'
	public static int BIGGEST_CHAR = 0x5A;
	// the number of characters that we will work with
	public static int NUMBER_CHARS = BIGGEST_CHAR - SMALLEST_CHAR + 1;

	// verschlüsseln

	public char encode(char chr) {
		int c = chr;
		if (c >= SMALLEST_CHAR && c <= BIGGEST_CHAR) {

			int code = this.code.charAt(counter) - SMALLEST_CHAR;
			c += code;

			if (c > BIGGEST_CHAR) {
				c -= NUMBER_CHARS;
			}
			counter = (counter < this.code.length() - 1) ? ++counter : 0;

		}
		return (char) c;
	}

	// entschlüsseln

	public char decode(char chr) {
		int c = chr;
		if (c >= SMALLEST_CHAR && c <= BIGGEST_CHAR) {

			int code = this.code.charAt(counter) - SMALLEST_CHAR;
			c -= code;

			if (c < SMALLEST_CHAR) {
				c += NUMBER_CHARS;
			}
			counter = (counter < this.code.length() - 1) ? ++counter : 0;

		}
		return (char) c;
	}

}
